﻿using Microsoft.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore.Modeling;
using Volo.Abp.EntityFrameworkCore.DependencyInjection;
using Joy.Erp.BasicArchives.EntityFrameworkCore;

namespace Joy.Erp.BasicArchives.ItemMasters
{
    public class ItemMasterModelConfiguration : IModelConfiguration
    {
        public void Build(ModelBuilder builder)
        {
            builder.Entity<ItemMaster>(b =>
            {
                b.ToTable(BasicArchivesDbProperties.DbTablePrefix + nameof(ItemMaster), BasicArchivesDbProperties.DbSchema);
                b.ConfigureByConvention();
                b.ConfigureArchiveAggregateRoot();

                b.Property(x => x.Name).HasMaxLength(ItemMasterConsts.NameMaxLength);
                b.Property(x => x.Name).IsRequired(ItemMasterConsts.NameRequired);
                b.Property(x => x.Spec).HasMaxLength(ItemMasterConsts.SpecMaxLength);
                b.Property(x => x.ItemCategoryId).IsRequired(ItemMasterConsts.ItemCategoryIdRequired);
                b.Property(x => x.UnitGroupId).IsRequired(ItemMasterConsts.UnitGroupIdRequired);

                b.HasOne(x => x.Category).WithMany().HasForeignKey(x => x.ItemCategoryId).OnDelete(DeleteBehavior.Restrict);
                b.HasOne(x => x.UnitGroup).WithMany().HasForeignKey(x => x.UnitGroupId).OnDelete(DeleteBehavior.Restrict);
            });
        }

        public void Entity(IAbpDbContextRegistrationOptionsBuilder options)
        {
            options.Entity<ItemMaster>(opt =>
            {
                opt.DefaultWithDetailsFunc = query =>
                {
                    return query
                        .Include(x => x.Category)
                        .Include(x => x.UnitGroup)
                            .ThenInclude(x => x.Children)
                        ;
                };
            });
        }
    }
}
